package cn.tworice.client.service;

import cn.tworice.common.util.excel.InductsListenerService;
import cn.tworice.api.CrudService;
import cn.tworice.client.dao.ShoppingCartDao;
import cn.tworice.common.entity.code.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCartService implements InductsListenerService<ShoppingCart>, CrudService<ShoppingCart> {
    @Autowired
    private ShoppingCartDao dao;

    @Override
    public List<ShoppingCart> list(Integer page, Integer pageSize, ShoppingCart entity) {
        return dao.queryList(page * pageSize, pageSize, entity);
    }

    @Override
    public int total(ShoppingCart entity) {
        return dao.queryTotal(entity);
    }

    @Override
    public int set(ShoppingCart entity) {
        List<ShoppingCart> shoppingCarts = dao.queryList(0, 10, entity);
        entity.setUpdateTime(System.currentTimeMillis());
        if(entity.getId()!=null){
            return dao.update(entity);
        }else {
            if (shoppingCarts.size() != 0) {
                ShoppingCart shoppingCart = shoppingCarts.get(0);
                shoppingCart.setGoodsNum(shoppingCart.getGoodsNum() + entity.getGoodsNum());
                return dao.update(shoppingCart);
            } else {
                entity.setUpdateTime(System.currentTimeMillis());
                entity.setCreateTime(System.currentTimeMillis());
                return dao.insert(entity);
            }
        }
    }

    @Override
    public boolean update(ShoppingCart entity) {
        return dao.update(entity) == 1;
    }

    @Override
    public int del(Integer[] ids) {
        return dao.del(ids);
    }

    @Override
    public int save(List<ShoppingCart> list) {
        list.forEach(item -> {
            item.setCreateTime(System.currentTimeMillis());
            item.setUpdateTime(System.currentTimeMillis());
        });
        return dao.insertList(list);
    }

    @Override
    public ShoppingCart info(int id) {
        return dao.queryInfo(id);
    }
}